package com.lagou.edu.factory;

import com.lagou.edu.annotation.MiniAutoWired;
import com.lagou.edu.annotation.MiniComponent;
import com.lagou.edu.annotation.MiniTransactional;
import com.lagou.edu.utils.TransactionManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.SQLException;

/**
 * @ClassName: ProxyFactory
 * @Auther: Jerry
 * @Date: 2020/6/30 14:59
 * @Desctiption: 动态代理工厂
 * @Version: 1.0
 */
public class ProxyFactory {

    private TransactionManager transactionManager;
    private ProxyFactory(){
        transactionManager = TransactionManager.newInstance();
    }

    private static ProxyFactory proxyFactory = new ProxyFactory();
    public static ProxyFactory newInstance(){
        return proxyFactory;
    }

    /**
     * 获得代理实例
     * @param target 目标
     * @return {@link Object}
     */
    public Object getProxyInstance(Object target){
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object result = null;
                try {
                    // 开启事务
                    transactionManager.beginTransaction();
                    result = method.invoke(target, args);
                    // 提交事务
                    transactionManager.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                    // 回滚事务
                    transactionManager.rollback();
                    throw e;
                }
                return result;
            }
        });
    }

}
